(function() {
	var imp, replace, copy, encode;
	importer();
	shortcuts();

	panda.fileName = function(req, name) {
		var ret = req.getParameter(name);
		ret = ret.substring(ret.lastIndexOf('/') + 1);
		ret = ret.substring(ret.lastIndexOf('\\') + 1);

		return ret;
	};
	
	panda.upload = function(req, name, dest) {
		dest = imp.File(dest);
		if (multipart(req)) {
			var src = req.getAttribute(name);
			copy(src.toPath(), dest.toPath(), replace);
		} else {
			var is = req.getInputStream();
			copy(is, dest.toPath(), replace);
		}

		return dest.length();
	};

	panda.download = function(req, res, name, src) {
		var encoded = encodeFileName(req, name);
		var disposition = "attachment; filename=\"" + encoded + '"';

		res.contentType = "application/octet-stream; charset=UTF-8";
		res.setHeader("Content-Disposition", disposition);

		copy(imp.File(src).toPath(), res.outputStream);
	};

	function importer() {
		imp = JavaImporter(
			java.io,
			java.net,
			java.lang,
			java.nio.file,
			javax.servlet.http);
	}

	function shortcuts() {
		replace = imp.StandardCopyOption.REPLACE_EXISTING;
		copy = imp.Files.copy;
		encode = imp.URLEncoder.encode;
	}

	function multipart(req) {
		return req.getHeader("Content-Type").startsWith("multipart");
	}

	function encodeFileName(req, name) {
		var agent = req.getHeader("USER-AGENT").toLowerCase();

		if (agent != null
				&& agent.indexOf("firefox") < 0
				&& agent.indexOf("safari") < 0) {
			return encode(name, "UTF8");
		}
		
		var bytes = imp.String(name).getBytes("UTF-8");
		return imp.String(bytes, "ISO8859-1");
	}
}());
